/*
 Copyright (c) Whitemice Consulting, 2007, 2008, 2009
 Adam Tauno Williams <awilliam@whitemice.org>
 License: MIT/X11

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/
using System;
using System.Linq;
using System.Collections.Generic;
using Whitemice.ZOGI;
using Whitemice.ZOGI.GtkWidgets;
using Whitemice.ZOGI.GtkFolios;

namespace Whitemice.Consonance
{
	public partial class ContactWindow : EntityWindow
	{
		protected Contact						      contact;
		protected ContactFolio			      folio;
		protected EnterpriseSearchDialog	enterpriseSearchDialog;			
		
		public ContactWindow(Contact _contact) : base(Gtk.WindowType.Toplevel)
		{
			this.Build();
			enterpriseSearchDialog = null;
			folio = new ContactFolio();
			folioArea.Child = folio;
			folio.ShowAll();
			folio.OnTabThaw += new EventHandler(ThawOneLevel);
			
			folio.EnterpriseTab.OnEnterpriseEdit += new EntityEventHandler(EnterpriseEdit);
			folio.EnterpriseTab.OnEnterpriseRemove += new EntityEventHandler(EnterpriseRemove);
			folio.EnterpriseTab.OnEnterpriseUnassign += new EntityEventHandler(EnterpriseUnassign);
			folio.LinksTab.OnEntityPresent += new EntityEventHandler(Present);
			
			Fill(_contact);
			ShowAll();
		} // end ctor

    public override Entity Current { get { return contact; } }
		
		protected void SetTitle()
		{
			if (contact.ObjectId < 0)
			{
				Title = "New Contact";
			} else
				{
					Title = "Contact#" + 
						contact.ObjectId.ToString() + ":" + 
						contact.LastName + ", " +
						contact.FirstName;
				}
		} // end SetTitle
		
    protected override void Fill(Entity entity)
    {
      this.EntityNameCheck(entity, typeof(Whitemice.ZOGI.Contact));
      contact = (entity as Whitemice.ZOGI.Contact);
      FreezeToDepth(1);
      Registry.RegisterForNotification(contact, this);
      folio.Fill(Current);
      SetTitle();
      if (contact.CanModify)
      {

      } else
        {

        }    
    }
		
    public override void ProcessEvent(Whitemice.ZOGI.ServerEvent e)
    {
      switch(e.Event)
      {
        case ServerEventType.Update:
          Fill(Current);
          break;
        case ServerEventType.SubordinateChange:
          folio.EnterpriseTab.Fill(contact);
          //folio.ProjectTab(enterprise);
          break;
      } // end event-switch
    } // end ReceiveEvent
		
		protected override bool Take()
		{
			return folio.Take(contact);
		} // end Take

    protected override void SaveCallback(Entity entity, Exception exception, object context)
    {
      if (exception == null)
      {
        SetTitle();
        Register(entity);
        this.ZLOG(string.Format("SaveCallback(objectId#{0})", entity.ObjectId));
        folio.Fill(entity);
      } else
        {
          new MessageBox(exception);
        }
      Thaw();
    }

		protected virtual void OnRemove(
			object _sender, 
			System.EventArgs _e)
		{
			Remove(contact);
		} // end OnRemoveClicked

		protected virtual void OnApplyClicked(
			object _sender, 
			System.EventArgs _e)
		{
			Save(contact, false);
		} // end OnApplyClicked

		protected virtual void OnCloseActivated(
			object sender, 
			System.EventArgs e)
		{
			Unregister(contact, true);
		} // end OnQuitActivated

    /// <summary>
    /// Assign enterprise to the contact
    /// </summary>
    /// <param name="enterpriseId">
    /// A <see cref="System.Int32"/>
    /// </param>
		public virtual void EnterpriseAssign(int enterpriseId)
		{
      //TODO: Make Asyncronous
      Entity entity;
      
      this.ZLOG("ContactId#{0} enterprise assign (EnterpriseId#{1})", 
                contact.ObjectId,
                enterpriseId);
      if (enterpriseId > 0)
      {
        entity = Server.Connection.Get(enterpriseId, 65535, true);
        if (entity == null)
        {
          this.ZLOG("Failed to retrieve EnterpriseId#{0}", enterpriseId);
        } else if (entity is Whitemice.ZOGI.Enterprise)
          {
            contact.Assign(entity);
            folio.EnterpriseTab.Fill(contact);
          } else
            {
              // TODO: Is it possible to arrive here?
            }
      }
		} // End AssignEnterprise
		
		protected virtual void EnterpriseEdit(
		  Entity entity,
			object context, 
			Exception ex)
		{
      this.ZLOG(string.Format("Contact#{0} enterprise edit (Enterprise#{1})", 
                              contact.ObjectId,
                              entity.ObjectId));
		  if (entity != null)
		    if (!(GUI.RaiseWindow(entity)))
				  new EnterpriseWindow((entity as Enterprise)); 
		} // end EnterpriseEdit

    //TODO: Test ContactWindow.EnterpriseRemove
		protected virtual void EnterpriseRemove(
		  Entity entity,
			object context, 
			Exception ex)
		{
      if (entity == null)
        throw new Exception("Null entity received by EnterpriseRemove");
      this.ZLOG(string.Format("Contact#{0} enterprise remove (Enterprise#{1})", 
                              contact.ObjectId,
                              entity.ObjectId));
			if (GUI.RaiseWindow(entity))
			{
				// Object is being viewed, present the window and notify user
				new MessageBox("Object#" + entity.ObjectId.ToString() + " is currently in use.");
			} else
				{
					if (entity.CanModify)
					{
            Freeze();
            DeleteCommand command = new DeleteCommand(entity, 
                                                      RpcPriority.Immediate, 
                                                      null, // no flags
                                                      0, // detail does not matter for deletion
                                                      new string[] { ":remove-child" });
            command.Callback = callback;
            Server.Connection.RunCommand(command);
					} else 
						{
							// Insufficient privileges to delete object
							new MessageBox("You lack sufficient privilages to perform the requested action");
						}
				} // end else-object-is-available
		} // end EnterpriseRemove

		protected virtual void EnterpriseUnassign(
		  Entity entity,
			object context, 
			Exception exception)
		{
      this.ZLOG(string.Format("Contact#{0} enterprise unassign (Enterprise#{1})", 
                              contact.ObjectId,
                              entity.ObjectId));
		  if (contact.CanModify)
		  {
        this.ZLOG("Applying unassignment");
		    contact.Unassign(entity);
		    folio.EnterpriseTab.Fill(contact);
		  } else new MessageBox("You lack sufficient privilages to perform the requested action");
		} // end EnterpriseUnassign

		protected virtual void OnOk (object sender, System.EventArgs e)
		{
		  Save(contact, true);
		}

		protected virtual void OnDeleteEvent (object o, Gtk.DeleteEventArgs args)
		{
		  Unregister(contact, true);
		} // end OnDeleteEvent

		protected virtual void OnRefresh (object sender, System.EventArgs e)
		{
      FetchCommand  command;
      command = new FetchCommand(contact.ObjectId, 
                                 65535, 
                                 new object[] { ":fill" } );
      command.UseCache = false;
      command.Callback = callback;
      Freeze();
      Server.Connection.RunCommand(command);
		} // end OnRefresh

		protected virtual void OnEnterpriseLinkActionActivated (object sender, System.EventArgs e)
		{
      this.ZLOG(string.Format("Contact#{0} enterprise link", contact.ObjectId));
		  if(contact.CanModify)
		  {
			  if (enterpriseSearchDialog == null)
		  	{
			  	enterpriseSearchDialog = new EnterpriseSearchDialog(
			  		ZOGIUtility.GetWindow(this), 
			  		contact.ObjectId,
					  "Assign enterprise to " + contact.LastName);
			    enterpriseSearchDialog.SetEnterpriseId += 
					  new EnterpriseSearchDialog.SetEnterpriseIdHandler(EnterpriseAssign);
				}
				enterpriseSearchDialog.Present();
		  }		
		} // end OnEnterpriseLinkActionActivated

		protected virtual void OnTaskAddActionActivated (object sender, System.EventArgs e)
		{
      this.ZLOG("Contact#{0} task add", contact);
    }

    protected override void RemoveCallback(Entity entity, Exception exception, object context)
    {
      this.ZLOG("RemoveCallback");
      if (exception == null)
      {
        Unregister(contact, true);
      } else
        {
          new MessageBox(exception);
          Thaw();
        }
    } // end RemoveCallback

    protected override void RemoveChildCallback(Entity entity, Exception exception, object context)
    {
      this.ZLOG("RemoveChildCallback");
      if (exception != null)
        new MessageBox(exception);
      Thaw();
    }
	} // end class 
} // end namespace 
